<!-- 登录页面 -->
<template>
  <div class="login-container">
    <van-tabs v-model:active="activeName">
      <van-tab title="用户名密码"
               name="username-password">
        <van-form @submit="onUsernameSubmit"
                  class="login-form-style">
          <van-cell-group inset>
            <van-field v-model="username"
                       name="username"
                       label="用户名"
                       placeholder="手机号/邮箱"
                       :rules="[{ required: true, message: '手机号/邮箱' }]" />
            <van-field v-model="password"
                       type="password"
                       name="password"
                       label="密码"
                       placeholder="密码"
                       :rules="[{ required: true, message: '请填写密码' }]" />
          </van-cell-group>
          <div v-if="error"
               class="error-class">用户名密码错误</div>
          <div class="forget-password-style">
            <a href="#">忘记密码</a>
          </div>
          <div class="btn-div-style">
            <van-button class="login-form-btn-style"
                        round
                        block
                        type="primary"
                        native-type="submit">
              登录
            </van-button>
          </div>
        </van-form>
      </van-tab>

      <!-- <van-tab title="手机号验证码"
               name="phone-code">
        <van-form @submit="onPhonecodeSubmit"
                  class="login-form-style">
          <van-cell-group inset>
            <van-field v-model="phone"
                       label="手机号"
                       name="phone"
                       type="tel"
                       placeholder="请输入手机号" />
            <van-field v-model="smsCode"
                       center
                       clearable
                       label="验证码"
                       name="smCode"
                       placeholder="请输入验证码">
              <template #button>
                <van-button size="mini"
                            style="height: 25px"
                            type="primary">发送验证码</van-button>
              </template>
            </van-field>
          </van-cell-group>
          <div v-if="errorPhone"
               class="error">手机号验证码错误</div>
          <div class="btn-div-style">
            <van-button class="login-form-btn-style"
                        round
                        block
                        type="primary"
                        native-type="submit">
              登录
            </van-button>
          </div>
        </van-form>
      </van-tab> -->
      <div class="no-accont-tip-style">
        没有账号？<span @click="gotoRegister"
              style="color:#0000EE">立即注册</span>
      </div>
    </van-tabs>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    //这里存放数据
    return {
      error: false,
      activeName: "username-password",
      // 用户名密码
      username: "",
      password: "",
      // 手机号短信验证码
      phone: "",
      smsCode: "",
    };
  },
  //方法集合
  methods: {
    // 提交
    onUsernameSubmit (formData) {
      var that = this;
      // 构造请求参数
      var params = {
        clientId: "system",
        clientSecret: "123456",
        ...formData,
      };
      // 构造请求头
      var header = {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        extendMap: '{"phone":"15656589658","userType":"user"}',
      };
      // 调用登录
      this.$http
        .post(this.$reqPrefix.oauth + "/oauth2/login", params, null, header)
        .then((data) => {
          // 如果登录成功保存数据去首页
          that.$store.commit(
            "login",
            data.data.access_token,
            data.data.refresh_token
          );
          // 调用接口获取当前登录人信息
          that.$http
            .get(this.$reqPrefix.user + "/im/users/current-login-user", {})
            .then(res => {
              // 获取当前登录人成功后存起来
              that.$store.commit(
                "setLoginUser",
                res.data,
              );
              // 使用手机号作为唯一标识
              that.$socket.config.identity = res.data.phone
              //使用promise在这里初始化连接，并将返回值实例赋给vue 实例
              Promise.resolve().then(function () {
                console.log('开始初始化socket...');
                let loginMessage = new proto.com.ouyu.im.Message();
                console.log(loginMessage);
                console.log(that.$socket.config);
                const socket = new Socket(that.$socket.config);
                console.log(socket);
                return socket;
              })
                .then(function (socket) {
                  if (socket) {
                    that.$store.commit(
                      "setSocket",
                      socket,
                    );

                    //延迟一段时间,不然可能内部的真实websocket 还没创建完成，这里等三秒中在执行
                    setTimeout(function () {
                      // 发送广播消息通知其他好友自己上线了
                      // 封装添加好友的消息类型
                      let broadcastMessage = new proto.com.ouyu.im.Message();
                      broadcastMessage.setFrom(that.$socket.config.identity);
                      broadcastMessage.setTo("");
                      broadcastMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
                      broadcastMessage.setContent("online");
                      // 时间戳毫秒
                      broadcastMessage.setCreateTime(new Date().getTime());
                      socket.send(broadcastMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_BROADCAST);
                    }, 5000);
                  }
                })
                .catch(function (err) {
                  console.log('socket 连接错误！%o', err);
                });


              // 登录成功去首页
              that.$router.push("/");


            }).catch(err => {
              console.error("获取当前登录人失败！")
            });
        })
        .catch((error) => {
          // 接口异常会走这里
          console.log("登录失败！");
          that.error = true;
        });
    },
    // 提交
    onPhonecodeSubmit (formData) {
      console.log("submit", formData);
    },
    gotoRegister () {
      this.$router.replace({ name: "Register" });
    },
  },

  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.login-container {
  position: absolute;
  height: 100%;
  width: 100%;
  background: whitesmoke;
}
.login-form-style {
  margin: 0.6rem;
}
.btn-div-style {
  display: flex;
  justify-content: center;
  .login-form-btn-style {
    width: 8rem;
    margin-top: 1rem;
  }
}
.forget-password-style {
  text-align: right;
  margin: 0.2rem 0.6rem;
}
.no-accont-tip-style {
  text-align: center;
}
.error-class {
  text-align: center;
  color: red;
}
</style>
